<template>
  <!--选择章节-->
  <view class="SelectStructPopup">
    <u-popup :show="isPopup" :round="15" mode="bottom" @close="onClose" safe-area-inset-bottom>
      <view class="title">选择章节</view>
      <view class="content">
        <picker mode="selector" :range="array" @change="bindPickerChange">
          <view class="select-qus flex flex-row between">
            <view class="flex flex-row item-center"><label>*</label>
              <view>选择题库</view>
            </view>
            <u-icon name="arrow-right" color="#999999"></u-icon>
          </view>
        </picker>
        <view class="search">
          <u--input
              placeholder="请输入关键字"
              prefixIcon="search"
              prefixIconStyle="font-size: 26px;color: #999999"
              customStyle="height: 30px;border:1px solid #F2F2F2;border-radius:12px"
              clearable
              v-model="keyword"
              @change="searchChange"
          ></u--input>
        </view>

        <Tree :list="keyword?keywordList:list" @updateExpand="updateExpand" @selectNode="selectNode"/>

      </view>
      <view class="footer">
        <view class="line"></view>
        <view class="close btn" @click="isPopup=false">取消</view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import {listStruct} from "@/myQuestionBank/services/myQuestionBankService";
import Tree from "@/improve/components/Tree.vue";
import _ from 'lodash';
export default {
  name: "SelectStructPopup",
  components: {Tree},
  props: {},
  data() {
    return {
      questionList: [],
      isPopup: false,
      subjectUuid: "",
      keyword: "",
      list: [],
      keywordList: [],
      array: [],
      index: 0
    }
  },
  methods: {
    async open(list) {
      this.questionList = list
      this.keyword = ""
      this.array = this.questionList.map(item => {
        return item.name
      })
      this.isPopup = true;
    },
    getList() {
      listStruct({subjectUuid: this.subjectUuid}).then(res => {
        this.list = res || []
        this.list.forEach(item => {
          item.parentId = null;//把第一级的父级id置空
        })
        this.nodeAddExpand(this.list)
      })
    },
    //添加expand属性
    nodeAddExpand(nodes) {
      nodes.forEach(item => {
        this.$set(item, 'expand', false);
        if (item.children && item.children.length > 0) {
          this.nodeAddExpand(item.children);
        }
      })
    },
    //展开收起
    updateExpand(node) {
      this.updateExpandById(this.list, node.id, null);
    },
    updateExpandById(nodes, id) {
      nodes.forEach(item => {
        if (item.id === id) {
          // 如果找到匹配的id，更新expand值
          item.expand = !item.expand;
        } else if (item.children && item.children.length > 0) {
          this.updateExpandById(item.children, id);
        }
      });
    },
    // 修改 expand 属性的函数
    updateExpandAllByRootId(data, id, fl) {
      for (const item of data) {
        // 如果当前节点是目标节点或其子节点，设置 expand 属性
        if (item.id === id || item.parentId === id) {
          item.expand = fl;
        }
        // 如果有子节点，递归修改
        if (item.children && item.children.length > 0) {
          this.updateExpandAllByRootId(item.children, id, fl);
        }
      }
    },

    // 查找根节点id
    findRootIdById(data, targetId) {
      // 如果目标 ID 本身就是根节点，直接返回
      if (data.some(item => item.id === targetId)) {
        return targetId;
      }
      let rootId = null;

      // 内部递归函数
      function recursiveSearch(items) {
        for (const item of items) {
          if (item.id === targetId) {
            rootId = item.parentId; // 找到目标 ID，存储其父 ID
            return true;
          }
          // 如果有子节点，递归查找
          if (item.children && item.children.length > 0) {
            if (recursiveSearch(item.children)) {
              rootId = item.id; // 返回最外层的 ID
              return true;
            }
          }
        }
        return false; // 如果没有找到
      }

      recursiveSearch(data);
      return rootId; // 返回找到的根节点 ID
    },
    searchFindNodeByName(nodes, name) {
      nodes.forEach(item => {
        if (item.name.indexOf(name) > -1) {
          const id = this.findRootIdById(this.list, item.id);
          this.updateExpandAllByRootId(this.list, id, true)  //全部展开
          //添加匹配项
          if (this.keywordList.findIndex((item) => item.id === id) === -1) {
            this.keywordList.push(this.list.find((item) => item.id === id));
          }
        } else if (item.children && item.children.length > 0) {
          this.searchFindNodeByName(item.children, name);
        }
      });
    },
    //选中章节
    selectNode(node) {
      this.$emit("structConfirm", node)
      this.isPopup = false;
    },
    //搜索
    searchChange: _.debounce(async function () {
      if (this.keyword) {
        this.keywordList = []
        this.searchFindNodeByName(this.list, this.keyword);
      }
    }),
    onClose() {
      this.isPopup = false;
      this.$emit("close")
    },
    bindPickerChange: function (e) {
      this.subjectUuid = this.questionList[e.detail.value].subjectUuid
      this.getList()
    },
  },
}
</script>
<style scoped lang="scss">
.SelectStructPopup {

  .title {
    color: #333333;
    font-size: 32rpx;
    font-weight: bold;
    margin-top: 32rpx;
    text-align: center;
  }

  .content {
    border-bottom: solid 1px #EEEEEE;

    .select-qus {
      padding: 0 20px;
      height: 45px;

      view:nth-child(1) {
        color: #333333;
        font-size: 32rpx;

        label {
          color: #f56c6c;
          margin-right: 4px;
          font-size: 18px;
        }
      }
    }

    .search {
      padding: 0 15px;
      margin-bottom: 14px;

      input {
        height: 40px !important;
      }
    }

    .list {
      padding: 39px 22px 0 25px;
    }

    .subject-item {
      & + .subject-item {
        margin-top: 60rpx;
      }
    }

  }

  .btn {
    height: 96rpx;
    text-align: center;
    line-height: 96rpx;
    color: #000000;
    font-size: 14px;
  }

  .line {
    width: 100%;
    background-color: #F2F2F2;
    height: 6rpx;
  }
}
</style>